//
//  UIDevice+XFMethod.m
//  xieyingze
//
//  Created by xieyingze on 16/6/29.
//  Copyright © 2016年 xieyingze. All rights reserved.
//

#import "UIDevice+Method.h"
#import <sys/sysctl.h>
#include <ifaddrs.h>
#include <arpa/inet.h>
#import <sys/socket.h>
#import <sys/sockio.h>
#import <sys/ioctl.h>
#import <net/if.h>
#import <arpa/inet.h>
#import "AppHeader.h"

@implementation UIDevice (Method)

/**
 *  经度
 */
+ (NSString *)longitude{
    return @"";
}

/**
 *  纬度
 */
+ (NSString *)latitude{
    return @"";
}

/**
 *  设备类型
 */
+ (NSString *)deviceType{
    
    return @"iOS";
}

/**
 *  uuid
 */
+ (NSString *)uuid{
//    return [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    return [[UnityTool shareInstance] getUUID];
}

/**
 *  系统版本
 */
+ (NSString *)deviceSystem{
    return [NSString stringWithFormat:@"iOS %@", [[UIDevice currentDevice] systemVersion]];
}

/**
 *  app版本
 */
+ (NSString *)appVersion{

    //build
//    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    //version
//    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    NSString *versionStr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSArray *arr = [versionStr componentsSeparatedByString:@"."];

    NSMutableString *paramVersion = [NSMutableString string];
    for (NSString *str in arr) {
        [paramVersion appendFormat:@"%02d",[str intValue]];
    }
    return paramVersion;
}

/**
 *  IP地址
 */
+ (NSString *)ipAddress
{
//    NSString *address = @"";
//    struct ifaddrs *interfaces = NULL;
//    struct ifaddrs *temp_addr = NULL;
//    int success = 0;
//
//    success = getifaddrs(&interfaces);
//
//    if (success == 0) { // 0 表示获取成功
//
//        temp_addr = interfaces;
//        while (temp_addr != NULL) {
//            if( temp_addr->ifa_addr->sa_family == AF_INET) {
//                // Check if interface is en0 which is the wifi connection on the iPhone
//                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
//                    // Get NSString from C String
//                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
//                }
//            }
//
//            temp_addr = temp_addr->ifa_next;
//        }
//    }
//
//    freeifaddrs(interfaces);
//
//    NSLog(@"手机的IP是：%@", address);
//    return address;
//    return @"192.168.0.0"

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    
    if (sockfd == 0) return nil;
    
    NSMutableArray *ips = [NSMutableArray array];
    
    
    
    int BUFFERSIZE = 4096;
    
    struct ifconf ifc;
    
    char buffer[BUFFERSIZE], *ptr, lastname[IFNAMSIZ], *cptr;
    
    struct ifreq *ifr, ifrcopy;
    
    ifc.ifc_len = BUFFERSIZE;
    
    ifc.ifc_buf = buffer;
    
    if (ioctl(sockfd, SIOCGIFCONF, &ifc) >= 0){
        
        for (ptr = buffer; ptr < buffer + ifc.ifc_len; ){
            
            ifr = (struct ifreq *)ptr;
            
            int len = sizeof(struct sockaddr);
            
            if (ifr->ifr_addr.sa_len > len) {
                
                len = ifr->ifr_addr.sa_len;
                
            }
            
            ptr += sizeof(ifr->ifr_name) + len;
            
            if (ifr->ifr_addr.sa_family != AF_INET) continue;
            
            if ((cptr = (char *)strchr(ifr->ifr_name, ':')) != NULL) *cptr = 0;
            
            if (strncmp(lastname, ifr->ifr_name, IFNAMSIZ) == 0) continue;
            
            memcpy(lastname, ifr->ifr_name, IFNAMSIZ);
            
            ifrcopy = *ifr;
            
            ioctl(sockfd, SIOCGIFFLAGS, &ifrcopy);
            
            if ((ifrcopy.ifr_flags & IFF_UP) == 0) continue;
            
            
            
            NSString *ip = [NSString  stringWithFormat:@"%s", inet_ntoa(((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr)];
            
            [ips addObject:ip];
            
        }
        
    }
    
    close(sockfd);
    
    
    NSString *deviceIP = @"";
    
    for (int i=0; i < ips.count; i++)
        
    {
        if (ips.count > 0)
            
        {
            deviceIP = [NSString stringWithFormat:@"%@",ips.lastObject];
        }
    }
    
    //    NSLog(@"%@", deviceIP);
    
    NSInteger ipCount = [deviceIP componentsSeparatedByString:@"."].count;
    
    //格式是否是IPV4，IPV6
    if (!(ipCount == 4 || ipCount == 6))  return [self randomIP];
    //内网 10.*.*.* , 192.168.*.*
    if ([deviceIP hasPrefix:@"192.168"] ||
        [deviceIP hasPrefix:@"10."]  )
    {
        return [self randomIP];
    }
    //内网 172.16.*.* --- 172.31.*.*
    int  secondIP = [[[deviceIP componentsSeparatedByString:@"."] objectAtIndex:1] intValue];
    if ([deviceIP hasPrefix:@"172."] && secondIP > 15 && secondIP < 32) return [self randomIP];
    
    //获取的是正确的ip
    return deviceIP;
    
}
/**
 *  手机型号
 */
+ (NSString *)deviceModel
{
//    return @"ipone 6s";
    
    size_t size;
    int nR = sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = (char *)malloc(size);
    nR = sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
    free(machine);
    
    if ([platform isEqualToString:@"iPhone1,1"]) {
        
        platform = @"iPhone 1G";
        
    }else if ([platform isEqualToString:@"iPhone1,2"]) {
        
        platform = @"iPhone 3G";
        
    }else if ([platform isEqualToString:@"iPhone2,1"]) {
        
        platform = @"iPhone 3Gs";
        
    }else if ([platform isEqualToString:@"iPhone3,1"]||[platform isEqualToString:@"iPhone3,2"]||[platform isEqualToString:@"iPhone3,3"]) {
        
        platform = @"iPhone 4";
        
    }else if ([platform isEqualToString:@"iPhone4,1"]) {
        
        platform = @"iPhone 4s";
        
    }else if ([platform isEqualToString:@"iPhone5,1"]||[platform isEqualToString:@"iPhone5,2"]) {
        
        platform = @"iPhone 5";
        
    }else if ([platform isEqualToString:@"iPhone5,3"]||[platform isEqualToString:@"iPhone5,4"]) {
        
        platform = @"iPhone 5C";
        
    }else if ([platform isEqualToString:@"iPhone6,2"]||[platform isEqualToString:@"iPhone6,1"]) {
        
        platform = @"iPhone 5s";
        
    }else if ([platform isEqualToString:@"iPhone7,2"]) {
        
        platform = @"iPhone 6";
        
    }else if ([platform isEqualToString:@"iPhone8,1"]) {
        
        platform = @"iPhone 6s";
        
    }else if ([platform isEqualToString:@"iPhone7,1"]) {
        
        platform = @"iPhone 6Plus";
        
    }else if ([platform isEqualToString:@"iPhone8,2"]) {
        
        platform = @"iPhone 6sPlus";
        
    }else if ([platform isEqualToString:@"iPhone9,1"]) {
        
        platform = @"iPhone 7";
        
    } else if ([platform isEqualToString:@"iPhone9,2"]) {
        
        platform = @"iPhone 7Plus";
        
    } else if ([platform isEqualToString:@"iPhone8,4"]) {
        
        platform = @"iPhone SE";
        
    } else if ([platform isEqualToString:@"iPhone10,1"]) {
        
        platform = @"iPhone 8";
        
    } else if ([platform isEqualToString:@"iPhone10,2"]) {
        
        platform = @"iPhone 8Plus";
        
    } else if ([platform isEqualToString:@"iPhone10,3"]) {
        
        platform = @"iPhone X";
        
    } else if ([platform isEqualToString:@"i386"] || [platform isEqualToString:@"x86_64"]) {
        
        platform = @"Simulator";
        
    }
    
    
    
    else if ([platform isEqualToString:@"iPod1,1"]) {
        
        platform = @"iPod Touch 1G";
        
    }else if ([platform isEqualToString:@"iPod2,1"]) {
        
        platform = @"iPod Touch 2G";
        
    }else if ([platform isEqualToString:@"iPod3,1"]) {
        
        platform = @"iPod Touch 3G";
        
    }else if ([platform isEqualToString:@"iPod4,1"]) {
        
        platform = @"iPod Touch 4G";
        
    }else if ([platform isEqualToString:@"iPod5,1"]) {
        
        platform = @"iPod Touch 5G";
        
    }
    
    
    else if ([platform isEqualToString:@"iPad1,1"]) {
        
        platform = @"iPad 1G";
        
    }
    else if ([platform isEqualToString:@"iPad2,2"]||[platform isEqualToString:@"iPad2,1"]||[platform isEqualToString:@"iPad2,3"]||[platform isEqualToString:@"iPad2,4"]) {
        
        platform = @"iPad 2";
        
    }else if ([platform isEqualToString:@"iPad3,1"]||[platform isEqualToString:@"iPad3,2"]) {
        
        platform = @"iPad 3";
        
    }else if ([platform isEqualToString:@"iPad3,4"]||[platform isEqualToString:@"iPad3,5"]||[platform isEqualToString:@"iPad3,6"]) {
        
        platform = @"iPad 4";
        
    }else if ([platform isEqualToString:@"iPad4,1"]||[platform isEqualToString:@"iPad4,2"]||[platform isEqualToString:@"iPad4,3"]) {
        
        platform = @"iPad Air";
        
    }
    else if ([platform isEqualToString:@"iPad2,5"]||[platform isEqualToString:@"iPad2,6"]||[platform isEqualToString:@"iPad2,7"]) {
        
        platform = @"ipad mini 1G";
        
    }else if ([platform isEqualToString:@"iPad4,4"]||[platform isEqualToString:@"iPad4,5"]||[platform isEqualToString:@"iPad4,6"]) {
        
        platform = @"ipad mini 2G";
        
    }
    
    
    return platform;
}


/**
 *  随机产生国内 公网ip
 *
 *  @return <#return value description#>
 */
+ (NSString *)randomIP {
    /**
     *  国内ip范围
     */
    NSArray *ipArr = [NSArray arrayWithObjects: @[@"607649792",@"608174079"],//36.56.0.0-36.63.255.255
                      @[@"1038614528",@"1039007743"],//61.232.0.0-61.237.255.255
                      @[@"1783627776",@"1784676351"],//106.80.0.0-106.95.255.255
                      @[@"2035023872",@"2035154943"],//121.76.0.0-121.77.255.255
                      @[@"2078801920",@"2079064063"],//123.232.0.0-123.235.255.255
                      @[@"-1950089216",@"-1948778497"],//139.196.0.0-139.215.255.255
                      @[@"-1425539072",@"-1425014785"],//171.8.0.0-171.15.255.255
                      @[@"-1236271104",@"-1235419137"], //182.80.0.0-182.92.255.255
                      @[@"-770113536",@"-768606209"],//210.25.0.0-210.47.255.255
                      @[@"-569376768",@"-564133889"], nil];//222.16.0.0-222.95.255.255
    int index = random()%10;
    NSArray *seleArr = ipArr[index];//选中的ip范围
    long num = [[seleArr firstObject] integerValue] + random()%([[seleArr lastObject] integerValue] - [[seleArr firstObject] integerValue]);
    return [self long2ip:num];
}
/**
 *  ip转长整形
 *
 *  @param ip ip
 *
 *  @return 长整形
 */
+ (long)ip2long:(NSString *)ip{
    NSArray *arr = [ip componentsSeparatedByString:@"."];
    long total = 0;
    for (int i = 0; i < 4; i ++) {
        total = total + ([arr[i] intValue] << ((3-i)*8));
    }
    NSLog(@"%zi",total);
    return total;
}
/**
 *  长整型转ip
 *
 *  @param num 长整形
 *
 *  @return ip
 */
+ (NSString *)long2ip:(long)num {
    //    num = 4244832000 + num;
    
    NSInteger one = num >> 24;
    NSInteger two = (num - (one << 24)) >> 16;
    NSInteger three = (num - (one << 24) - (two << 16))  >> 8;
    NSInteger four = num - (one << 24) - (two << 16) - (three << 8);
    
    if (num < 0) one = one + 256;
    NSLog(@"%zi.%zi.%zi.%zi",one,two,three,four);
    return [NSString stringWithFormat:@"%zi.%zi.%zi.%zi",one,two,three,four];
}
@end
